<?php
/**
 * @file			realTimeHook.class.php
 * @CopyRight		(C)1996-2099 SINA Inc.
 * @Project			自游网
 * @Author			liujz <jianzhou@staff.sina.com.cn>
 * @Create Date:	2012-01-09
 * @Modified By:	jianzhou/2012-01-09
 * @Brief			建筑的相关逻辑封装
 */
class building_class 
{
	
	// 初始化用户场景
	function initScene($uid)
	{
		if ( empty($uid) ) { return false; }
		
		$buildList 	= vApi::cfg('init_building');
		$db		 	= vApi::DB();
		$idList		= array_keys($buildList);
		$cfgList	= Building::getOne()->batchGet($idList); 
		
		$valList 	= array();
		foreach ($cfgList as $bid=>$cfg) 
		{
			$build		= $buildList[$bid];
			$valList[] 	= $db->SQL("('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')", $uid,$bid,$build['x'],$build['y'],$cfg['xlen'],$cfg['ylen'],$cfg['name'],$build['level'],$build['type'],APP_LOCAL_TIMESTAMP);
		}
		$valStr = implode(',', $valList);
		
		// Add To DB
		$sql = $db->SQL("INSERT INTO `%s` (`uid`,`bid`,`x`,`y`,`xlen`,`ylen`,`name`,`level`,`type`,`create_time`) VALUES $valStr", $db->getTable(API_TB_USER_BUILDING));
		$rs	 = $db->execute($sql);
		$rs  = $db->getAffectedRows();
		
		// 更新缓存
		if ( $rs )
		{
			$oBuild  = vApi::getBase('user_building');
			$bidList = $oBuild->cacheCall('getByUid_db', array($uid), array('kname'=>'user_building','kvar'=>"uid=$uid"), TRUE);
			$oBuild->mutiCacheCall('batchGet_db', array(''), array('kname'=>'user_building','kvars'=>$bidList['id']), TRUE);
		} 
		return $rs;
	}
	
	
	// 获取用户场景
	function getScene($uid)
	{
		if (empty($uid)) { return false; }
		
		// 获取场景, 初始化用户的建筑
		$scene	= vApi::getClass('zuobiao')->get();
		$list	= vApi::getBase('user_building')->getBuildByUid($uid, TRUE);
		
		$buildList   = $list['bd']; 
		$buildList[] = $list['m'];	// 主城
		foreach ($buildList as $aBuild)
		{
			$x = $aBuild['x'];
			$y = $aBuild['y'];
			for($yi=0; $yi<$aBuild['ylen']; $yi++)
			{
				for($xi=0; $xi<$aBuild['xlen']; $xi++) {
					$scene[$y+$yi][$x+$xi] = $aBuild['id'];
				}
			}
		}
		return $scene;
	}
	
	
	// 检查是否可建
	function chkXyBuild($scene, $x, $y, $bcfg)
	{
		for($yi=0; $yi<$bcfg['ylen']; $yi++)
		{
			for($xi=0; $xi<$bcfg['xlen']; $xi++) 
			{
				if (!isset($scene[$y+$yi][$x+$xi]) || $scene[$y+$yi][$x+$xi]) { return false; }
			}
		}
		return TRUE;
	}
	
	// 清空某建筑的坐标
	function clearBuild($scene, $x, $y, $bcfg)
	{
		for($yi=0; $yi<$bcfg['ylen']; $yi++)
		{
			for($xi=0; $xi<$bcfg['xlen']; $xi++) 
			{
				if ( empty($scene[$y+$yi][$x+$xi]) ) { continue; }
				$scene[$y+$yi][$x+$xi] = 0;
			}
		}
		return $scene;
	}
}